<?php


class Dragonfly_TPL_HTML extends \Poodle\TPL
{
	public
		$tpl_header = null,
		$tpl_footer = null,
		$tpl_layout = null,

		$body = '',
		$DTD  = 'html5';

	protected
		$tpl_path = 'themes/default/',
		$tpl_name = 'default';

	function __construct()
	{
		parent::__construct();

		if (defined('ADMIN_PAGES')) {
			$theme = 'admin';
		} else {
			global $MAIN_CFG, $CPG_SESS;
			$theme = $MAIN_CFG['global']['Default_Theme'];
			if ($MAIN_CFG['member']['allowusertheme'] || is_admin()) {
				if (isset($_GET['prevtheme'])) {
					if (!preg_match('#^([a-zA-Z0-9_\-]+)$#', $_GET['prevtheme'], $theme)) {
						cpg_error(sprintf(_ERROR_BAD_CHAR, 'theme'), _SEC_ERROR);
					}
					$theme = $CPG_SESS['prevtheme'] = $theme[1];
				} else if (!empty($CPG_SESS['prevtheme'])) {
					$theme = $CPG_SESS['prevtheme'];
				} else if ($MAIN_CFG['member']['allowusertheme'] && is_user() && Dragonfly::getKernel()->IDENTITY->theme) {
					$theme = Dragonfly::getKernel()->IDENTITY->theme;
				}
			}
			$CPG_SESS['theme'] = $theme = file_exists("themes/{$theme}/theme.php") ? $theme : 'default';
		}

		$this->setTPLName($theme);
	}

	public function setTPLName($name)
	{
		if (preg_match('#^[a-z0-9_]+$#', $name) && is_dir('themes/'.$name)) {
			$this->tpl_name = $name;
			$this->tpl_path = "themes/{$name}/";
		}
	}

	public function display($filename, $data=null, $mtime=0, $options=0)
	{
		if (!defined('HEADER_OPEN')) { include('header.php'); }
		if ('header'===$filename && ($this->tpl_header || $this->tpl_layout)) {
			if ($this->tpl_header) {
				parent::display($this->tpl_header, null, 0, \Poodle\TPL::OPT_PUSH_DOCTYPE);
				$this->tpl_header = null;
			}
		} else if ('footer'===$filename && ($this->tpl_footer || $this->tpl_layout)) {
			if ($this->tpl_footer) {
				parent::display($this->tpl_footer, null, 0, \Poodle\TPL::OPT_END_PARSER);
				$this->tpl_footer = null;
			} else {
				parent::display('layouts/'.$this->tpl_layout, null, 0, \Poodle\TPL::OPT_PUSH_DOCTYPE || \Poodle\TPL::OPT_END_PARSER);
			}
		} else if ($this->tpl_layout) {
			$this->body .= $this->toString($filename, $data, $mtime);
		} else {
			return parent::display($filename, $data, $mtime, $options);
		}
	}
}
